//
//  WNSubVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/31.
//

import UIKit

class WNSubVC: WNBaseVC {

    lazy var subView: SubTopView = {
        let view = SubTopView()
        return view
    }()

    lazy var subBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 18)
        btn.rx.tap.bind{ [weak self] in
            self?.tapSubBtn()
        }.disposed(by: rx.disposeBag)
        btn.wn_cornerWithBorder(8)
        return btn
    }()
    
    lazy var subTextView: IQTextView = {
        let view = IQTextView()
        view.font = .wn_font(name: .bold, size: 12)
        view.showsVerticalScrollIndicator = false
        view.wn_appendLinkString(string: "1. 從購買後的第二天開始每天登錄，點擊「簽到」並每天領取簽到禮物。\n2. 您可以連續30天收到簽到禮物。\n訂閱協議\n付款：購買費用將從您的Apple Store帳戶中扣除。 \n續訂：您的訂閱將自動續訂。訂閱將在每個結算期自動扣除，無論是每月還是其他期間，您可能會在每個結算期開始前24小時內被收取費用，直到您取消訂閱。\n取消：您可以在續訂日期前24小時的任何時間取消訂閱。\n\n管理：")
        view.wn_appendLinkString(string: "您可以查看、更改或取消您的訂閱。", withURLString: "https://apps.apple.com/account/subscriptions")
        view.textColor = .init(named: "gray_999999")
        view.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.init(named: "red_FE95B4")!]
        view.isEditable = false
        view.delegate = self
        view.contentInset = .init(top: -10, left: 0, bottom: 0, right: 0)
        return view
    }()

    lazy var privacyView: IQTextView = {
        let view = IQTextView()
        view.font = .wn_font(name: .bold, size: 12)
        view.showsVerticalScrollIndicator = false
        view.wn_appendLinkString(string: "《服務協議》", withURLString: WNConfigure.WNURL.wn_Agreement)
        view.wn_appendLinkString(string: "和")
        view.wn_appendLinkString(string: "《隱私政策》", withURLString: WNConfigure.WNURL.wn_Privacy)
        view.wn_appendLinkString(string: "\n《訂閱服務協議》")
        view.textColor = .init(named: "gray_999999")
        view.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.init(named: "gray_666666")!]
        view.isEditable = false
        view.delegate = self
        view.contentInset = .init(top: -10, left: 0, bottom: 0, right: 0)
        view.textAlignment = .center
        return view
    }()
    
    var subModel: SubModel? {
        didSet {
            subView.model = subModel
            handleCheckStatus()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewConfig() {
        view.addSubview(subView)
        view.addSubview(subBtn)
        view.addSubview(privacyView)
        view.addSubview(subTextView)
        subView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight+40)
            make.left.right.equalTo(0)
            make.height.equalTo(scaleWidth(162))
        }
        subBtn.snp.makeConstraints { make in
            make.top.equalTo(subView.snp.bottom).offset(20)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(44)
        }
        privacyView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-TabBarMargin-12)
            make.width.equalTo(300)
            make.height.equalTo(30)
        }
        subTextView.snp.makeConstraints { make in
            make.top.equalTo(subBtn.snp.bottom).offset(20)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(privacyView.snp.top).offset(-20)
        }
    }
    
    override func dataConfig() {
        pageName = "VIP"
        navView.titleName = "VIP"
        navView.rightBtnTitle = "恢復購買"
        navView.rightClosure = { [weak self] in
            WNSubManager.shared.restoreSubscribe(self?.subModel?.sub?.pid ?? "", self?.subModel?.sub?.password ?? "")
        }
        getSubDetail()
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.subscribeNoti, object: nil, queue: nil) { [weak self] not in
            self?.getSubDetail()
            self?.subModel?.isDing = 1
        }
    }
}

extension WNSubVC: UITextViewDelegate {
    
    func tapSubBtn() {
        if subBtn.titleLabel?.text == "儲值" {
            WNBuriedManager.shared.logProductItem(subModel?.sub?.pid ?? "", subModel?.sub?.name ?? "", subModel?.sub?.price ?? 0.0)
            WNSubManager.shared.creatSubscribeOrder(subModel?.sub?.pid ?? "", subModel?.sub?.price ?? 0.0)
        }else if subBtn.titleLabel?.text == "簽到" {
            checkInRequest()
        }
    }

    func handleCheckStatus() {
        if subModel?.isDing == 1 {
            if subModel?.checkInOrNOt == 1 {
                subBtn.setTitle("已領取", for: .normal)
                subBtn.backgroundColor = .init(named: "gray_E0E8EE")
            }else {
                subBtn.setTitle("簽到", for: .normal)
                subBtn.backgroundColor = WNColor.Fade().left2right(.init(width: ScreenW-40, height: 44))
            }
        }else {
            subBtn.setTitle("儲值", for: .normal)
            subBtn.backgroundColor = WNColor.Fade().left2right(.init(width: ScreenW-40, height: 44))
        }
    }
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == WNConfigure.WNURL.wn_Privacy {
            wn_pushWebVC(URL.absoluteString, "隱私政策")
        }
        if URL.absoluteString == WNConfigure.WNURL.wn_Privacy {
            wn_pushWebVC(URL.absoluteString, "服務協議")
        }
        if URL.absoluteString == "https://apps.apple.com/account/subscriptions" {
            if UIApplication.shared.canOpenURL(URL) {
                UIApplication.shared.open(URL, options: [:], completionHandler: nil)
            }
        }
        return false
    }

    func getSubDetail() {
        provider_recommend.rx.request(.getSubDetail)
            .asObservable().mapModel(BaseModel<SubModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let data = model.data {
                    self?.subModel = data
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
    
    func checkInRequest() {
        provider_recommend.rx.request(.checkInSub)
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let _ = model.data {
                    self?.wn_toast("Check in successed")
                    self?.getSubDetail()
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
}
